<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 盈联11
 */
class Yinglian11Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']) {
            //银联扫码
            case 11:
                $bankcode = 'ALIPAY';
                $tongdao = 'WSFSM';
                break;
            //银联快捷
            case 13:
                $bankcode = 'ALIPAY';
                $tongdao = 'WSFKJ';
                break;
            //网银跳转
            case 5:
            case 6:
                $bankcode = 'ALIPAY';
                $tongdao = 'WSFWG';
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $data = array(
            "pay_memberid" => $this->config['mch_id'],
            "pay_orderid" => $return['orderid'],
            "pay_amount" => $return['amount'],
            "pay_applydate" => date("Y-m-d H:i:s",time()),
            "pay_bankcode" => $bankcode,
            "pay_notifyurl" => $return['notifyurl'],
            "pay_callbackurl" => $return['callbackurl']
        );

        ksort($data);

        $str = '';
        foreach($data as $k=>$v){
            $str .= "{$k}=>{$v}&";
        }
        $str .= "key=".$this->config['signkey'];
        $data['pay_md5sign'] = strtoupper(md5($str));
        $data["pay_bankname"] = '';
        $data["pay_card_no"] = '';
        $data["pay_playerid"] = 'wanglianfu';
        $data["pay_requestIp"] = getIP();
        $data["tongdao"] = $tongdao;
        $data["return_type"] = 1;

        //po($this->config['gateway'], $data);

        $res = $origin = curl($this->config['gateway'], httpstr($data));
		
        $res = json_decode($res, true);
		
		/* echo '<pre/>'; print_r($data);
		
		echo "请求地址：" . $this->config['gateway']."<br/><br/>";
		echo "返回数据：";
		echo $origin . '<br/>';
		print_r($res); exit; */
		
		$code = $res['pay_url'];
		
		if(!$code){
			if($origin && strlen($origin)<100){
				$this->showmessage($origin,['code'=>C("THIRDCODES.".$this->class)]);
			}
			
			$this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
		}
		
		switch($this->config['paytype']) {
            //网银跳转
            case 5:
            case 6:
            //银联快捷
            case 13:
				header("Location:{$code}"); exit;
			default:
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
                if(!$isMobile){
                    $this->display("WeiXin/weixin");
                }else{
                    $this->display("WeiXin/weixinwap");
                }
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
            case 17:
            case 18:
                if($isMobile){
					header("Location:{$code}"); 
                    //$this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);
		
		//$this->debug_callback();

        if(!$this->checkip(getIP(), $this->yinglianip())){
            exit("wrong");
        }
        $p = I("get.");
        /*$p = array (
            'memberid' => '10120',
            'orderid' => '2018121321392355945',
            'amount' => '10.000',
            'datetime' => '20181213213935',
            'returncode' => '00',
            'sign' => '59BAA9B51F2AA5568F4735BD7315506F',
            'reserved1' => '',
            'reserved2' => '',
            'reserved3' => '',
        );*/

        //获取订单信息
        $orderid = $p['orderid'];
        $find = $this->checkOrderNotify($orderid);

        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        /*M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            //"pay_orderid_rd"=>$p['transaction_id']
        ));*/

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $ReturnArray = array( // 返回字段
            "memberid" => $p["memberid"], // 商户ID
            "orderid" =>  $p["orderid"], // 订单号
            "datetime" =>  $p["datetime"], // 交易时间
            "amount" =>  $p["amount"], // 交易金额
            "returncode" => $p["returncode"]
        );

        $key = $this->config['signkey'];

        ksort($ReturnArray);

        $str = "";
        foreach ($ReturnArray as $k => $v) {
            if($v === ''){
                continue;
            }
            $str .= $k."=>".$v."&";
        }
        $str .= "key=".$key;

        $sign = $p['sign'];
        $sign2 = strtoupper(md5($str));

        if($sign !== $sign2){
            exit("sign_wrong");
        }
        if($p['returncode'] !== '00'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'ok');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}